package com.meixiang.main;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.login.LoginActivity;
import com.meixiang.entity.VersionInfo;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.fragment.CalendarFragment;
import com.meixiang.fragment.HomeFragment;
import com.meixiang.fragment.MomentsFragment;
import com.meixiang.fragment.MyFragment;
import com.meixiang.global.AbActivityManager;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalConventionalData;
import com.meixiang.global.apiConfig;
import com.meixiang.gtapi.GeTuiPushReceiver;
import com.meixiang.gtapi.GetuiSdkHttpPost;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbToastUtil;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yicheng.android.ui.materialdesignlibrary.views.LayoutRipple;

import static com.meixiang.main.MXApplication.mApp;


/**
 * 作者：黑哥
 * <p>
 * 四个主界面
 */

public class MainActivity extends BaseActivity {
    @Bind(R.id.tab_home_icon)
    ImageView tabHomeIcon;
    @Bind(R.id.tab_home_text)
    TextView tabHomeText;
    @Bind(R.id.tab_home)
    LayoutRipple tabHome;
    @Bind(R.id.tab_calendar_icon)
    ImageView tabCalendarIcon;
    @Bind(R.id.tab_calendar_text)
    TextView tabCalendarText;
    @Bind(R.id.tab_calendar)
    LayoutRipple tabCalendar;
    @Bind(R.id.tab_moments_icon)
    ImageView tabMomentsIcon;
    @Bind(R.id.tab_moments_text)
    TextView tabMomentsText;
    @Bind(R.id.tab_moments)
    LayoutRipple tabMoments;
    @Bind(R.id.tab_my_icon)
    ImageView tabMyIcon;
    @Bind(R.id.tab_my_text)
    TextView tabMyText;
    @Bind(R.id.tab_my)
    LayoutRipple tabMy;
    //首页Fragment


    private HomeFragment homeFragment;
    //日程Fragment


    private CalendarFragment calendarFragment;
    //社区Fragment


    private MomentsFragment momentsFragment;
    //我的Fragment


    private MyFragment myFragment;
    //Fragment管理器 获取Fragment的实例


    private FragmentManager fragmentManager;
    //Fragment事物   进行添加,移除,替换,以及执行其他动作。


    private FragmentTransaction transaction;


    // SDK参数，会自动从Manifest文件中读取，第三方无需修改下列变量，请修改AndroidManifest.xml文件中相应的meta-data信息。


    private static final String MASTERSECRET = "5xdYGA8J296Z37GZdXBdQ8";


    // 修改方式参见个推SDK文档


    private String appkey = "";
    private String appsecret = "";
    private String appid = "";

    private static final int REQUEST_PERMISSION = 0;

    private SimpleDateFormat formatter;
    private Date curDate;
    public static TextView tView;
    public static TextView tLogView;
    private IWXAPI api;
    //融云token


    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        ButterKnife.bind(this);
        /**初始化分享*/

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(MainActivity.this, apiConfig.WX_APP_ID, false);
        //注册到微信
        api.registerApp(apiConfig.WX_APP_ID);
        /**初始化个推SDK*/
//        initGeTui();
        /**启动个推SDK*/
        PushManager.getInstance().initialize(this.getApplicationContext());


        Log.e("TAG", "启动了吗");
        /**开启*/
        doOpenGeTui();


        super.onCreate(savedInstanceState);
    }


    private void initGeTui() {
        // 从AndroidManifest.xml的meta-data中读取SDK配置信息


        String packageName = getApplicationContext().getPackageName();
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                appid = appInfo.metaData.getString("PUSH_APPID");
                appsecret = appInfo.metaData.getString("PUSH_APPSECRET");
                appkey = appInfo.metaData.getString("PUSH_APPKEY");

                Log.e("TAG", "key   appid=" + appid + "-appsecret=" + appsecret + "-appkey=" + appkey);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        // SDK初始化，第三方程序启动时，都要进行SDK初始化工作


        Log.d("GetuiSdkDemo", "initializing sdk...");
        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限


        boolean sdCardWritePermission =
                pkgManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
        // read phone state用于获取 imei 设备信息


        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作


            PushManager.getInstance().initialize(this.getApplicationContext());
        }

        /**

         * 应用未启动, 个推 service已经被唤醒,显示该时间段内离线消息

         */
        if (GeTuiPushReceiver.payloadData != null) {
//            tLogView.append(GeTuiPushReceiver.payloadData);


            Log.e("TAG", "示该时间段内离线消息" + GeTuiPushReceiver.payloadData);
        }

    }

    private void doOpenGeTui() {
        if (isNetworkConnected()) {
            // 不推荐在现网系统使用1.0版服务端接口，请参考最新的个推服务端API接口文档，使用最新的2.0版接口


            Map<String, Object> param = new HashMap<String, Object>();
            param.put("action", "pushmessage"); // pushmessage为接口名，注意全部小写

                /*---以下代码用于设定接口相应参数---*/
            param.put("appkey", appkey);
            param.put("appid", appid);
            // 注：透传内容后面需用来验证接口调用是否成功，假定填写为hello girl~


            param.put("data", "收到一条透传测试消息");
            curDate = new Date(System.currentTimeMillis());
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            param.put("time", formatter.format(curDate)); // 当前请求时间，可选

//            String cid = tView.getText().toString();


//            Log.e("TAG","得到cid=="+cid);


            param.put("clientid", "null"); // 您获取的ClientID

            param.put("expire", 3600); // 消息超时时间，单位为秒，可选


            // 生成Sign值，用于鉴权


            param.put("sign", GetuiSdkHttpPost.makeSign(MASTERSECRET, param));

            GetuiSdkHttpPost.httpPost(param);
        } else {
            Toast.makeText(this, "对不起，当前网络不可用!", Toast.LENGTH_SHORT).show();
        }


    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);

    }


    @Override
    protected void initView() {
        //初始化4个tab按钮
        //检测版本跟新
        //checkVersion(0);
    }
    /**
     * @param type 0:启动时检测更新
     *             1：点击检测更新
     */
    private void checkVersion(final int type) {
        HttpUtils.get(Config.VERSIONS_UPDATA, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                final VersionInfo info = new Gson().fromJson(result.toString(), VersionInfo.class);
                String currentVersion = Tool.getAppVersionName(context);
                if (Tool.compare(info.getVersion(), currentVersion) == 1) {

                    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
                    dialog.setTitle("发现新版本" + info.getVersion());
                    dialog.setMessage(info.getContent());
                    dialog.setCancelable(false);


                    if (type == 0 && info.getIsForcedUpdating().equals("true")) {

                    } else {
                        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                    }
                    dialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.getUrl()));
                            startActivity(intent);
                        }
                    });
                    dialog.show();
                } else {
                    if (type == 0) {

                    } else if (type == 1) {
                        Toast.makeText(context, "已是最新版本", Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onError(String code, String message) {

            }
        });

    }

    @Override
    protected void setData() {
        fragmentManager = getSupportFragmentManager();
        switchTab(0);
        //登录才能获取 要不然会报401
        if (mApp.hasLogin()) {
            GlobalConventionalData.getEvaluateStart(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //回退回来检查版本跟新
        checkVersion(0);

        if (MXApplication.mApp.hasLogin()) {
            if (mApp.hasLogin()) {
                //美保险实名认证时，当我的界面为空的时候，需要获取用户数据刷新状态
                if (myFragment == null) {
                    getUserinfo();
                }
            }
        }
    }

    //初始化当前的tab
    private void initTab() {
        tabHomeIcon.setImageResource(R.mipmap.home_undefined);
        tabCalendarIcon.setImageResource(R.mipmap.schedule_undefined);
        tabMomentsIcon.setImageResource(R.mipmap.community_undefined);
        tabMyIcon.setImageResource(R.mipmap.my_undefined);

        tabHomeText.setTextColor(ContextCompat.getColor(context, R.color.gray_cf));
        tabCalendarText.setTextColor(ContextCompat.getColor(context, R.color.gray_cf));
        tabMomentsText.setTextColor(ContextCompat.getColor(context, R.color.gray_cf));
        tabMyText.setTextColor(ContextCompat.getColor(context, R.color.gray_cf));
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (calendarFragment != null) {
            transaction.hide(calendarFragment);
        }
        if (momentsFragment != null) {
            transaction.hide(momentsFragment);
        }
        if (myFragment != null) {
            transaction.hide(myFragment);
        }
    }

    public void switchTab(int index) {
        initTab();
        transaction = fragmentManager.beginTransaction();
        hideFragment(transaction);
        switch (index) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.container, homeFragment);
                } else {
                    transaction.show(homeFragment);
                }
                tabHomeIcon.setImageResource(R.mipmap.home);
                tabHomeText.setTextColor(ContextCompat.getColor(context, R.color.magenta));
                break;
            case 1:
                if (calendarFragment == null) {
                    calendarFragment = new CalendarFragment();
                    transaction.add(R.id.container, calendarFragment);
                } else {
                    transaction.show(calendarFragment);
                }
                tabCalendarIcon.setImageResource(R.mipmap.schedule);
                tabCalendarText.setTextColor(ContextCompat.getColor(context, R.color.magenta));
                break;
            case 2:
                if (momentsFragment == null) {
                    momentsFragment = new MomentsFragment();
                    transaction.add(R.id.container, momentsFragment);
                } else {
                    transaction.show(momentsFragment);
                }

                tabMomentsIcon.setImageResource(R.mipmap.community);
                tabMomentsText.setTextColor(ContextCompat.getColor(context, R.color.magenta));
                break;
            case 3:
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    transaction.add(R.id.container, myFragment);
                } else {
                    // 如果indexFragment不为空，则直接将它显示出来


                    transaction.show(myFragment);
                }
                tabMyIcon.setImageResource(R.mipmap.my);
                tabMyText.setTextColor(ContextCompat.getColor(context, R.color.magenta));
                break;

        }

        transaction.commit();
    }

    @Override
    protected void initTitle() {
        // TODO Auto-generated method stub

    }

    //再按一次退出程序
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                exitTime = System.currentTimeMillis();
                AbToastUtil.showToast(this, "再按一次退出程序");
            } else {
                AbActivityManager.getInstance().clearAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.tab_home, R.id.tab_calendar, R.id.tab_moments, R.id.tab_my})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.tab_home:
                switchTab(0);
                break;
            case R.id.tab_calendar:
                switchTab(1);
                break;
            case R.id.tab_moments:
                if (!mApp.hasLogin()) {
                    startActivity(LoginActivity.class);
                } else {
                    switchTab(2);
                }

                break;
            case R.id.tab_my:
                switchTab(3);
                break;
        }
    }

    private void getToken() {
        HttpUtils.post(Config.RONGCLOUD_GET_TOKEN, null, new HttpCallBack(MainActivity.this) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.e("TAG", "得到token=" + result.toString());
                token = result.optString("token");
                Log.e("TAG", "得到token=====" + token);
                AbToastUtil.showToast(MainActivity.this, message);
                /**融云链接*/
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(MainActivity.this, message);
            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext());
            } else {
                Log.e("GetuiSdkDemo",
                        "we highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                                + "functions will not work");
                PushManager.getInstance().initialize(this.getApplicationContext());
            }
        } else {
            onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onDestroy() {
        Log.d("GetuiSdkDemo", "onDestroy()");
        GeTuiPushReceiver.payloadData.delete(0, GeTuiPushReceiver.payloadData.length());
        super.onDestroy();
    }

    @Override
    public void onStop() {
        Log.d("GetuiSdkDemo", "onStop()");
        super.onStop();
    }

    public boolean isNetworkConnected() {
        // 判断网络是否连接

        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return mNetworkInfo != null && mNetworkInfo.isAvailable();
    }


    private void getUserinfo() {
        HttpParams params = new HttpParams();
        HttpUtils.post(Config.USERINFO_URL, params, new HttpCallBack(this, "正在加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                mApp.clearUser();
                UserInfo mUserInfo = new Gson().fromJson(result.toString(), UserInfo.class);
                HashMap<String, String> vals = new HashMap<String, String>();
                vals.put("memberId", result.optString("memberId"));
                mApp.getSession().set(vals);
                mApp.setUser(mUserInfo);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}
